from minio import Minio
import urllib3
import yaml
import os
import sys
from pathlib import Path

ROOT = os.getcwd()
CONFIG_PATH = os.environ.get("CONFIG_YAML_PATH", os.path.join(ROOT, "config/config.yaml"))
print("using " + CONFIG_PATH)

with open(CONFIG_PATH, 'r') as f:
    CP = yaml.safe_load(f.read())
CP["model"]["path"] = ROOT + "/" + CP["model"]["path"]

mysql_conf = CP["mysql"]
gp_conf = CP["gp"]
minio_conf = CP["minio"]

GP_URL = gp_conf["url"]
GP_USER = gp_conf["user"]
GP_PASSWORD = gp_conf["password"]
GP_DRIVER = gp_conf["driver"]
GP_HOST = gp_conf["host"]
GP_PORT = gp_conf["port"]
GP_DBNAME = gp_conf["dbname"]
GP_MAX_CONN = 20
GP_MIN_CONN = 1

GP_PROP = {"user": GP_USER,
           "password": GP_PASSWORD,
           "driver": GP_DRIVER}

# MYSQL
MYSQL_USER = mysql_conf["user"]
MYSQL_PASSWORD = mysql_conf["password"]
# MYSQL_DRIVER = mysql_conf["driver"]
MYSQL_DBNAME = mysql_conf["dbname"]
# MYSQL_URL = mysql_conf["url"]
MYSQL_PORT = mysql_conf["port"]
MYSQL_HOST = mysql_conf["host"]

# MYSQL_PROP = {"user": MYSQL_USER,
#               "password": MYSQL_PASSWORD,
#               "driver": MYSQL_DRIVER}

MINIO_ADDRESS = minio_conf["address"]
MINIO_ACCESS_KEY = minio_conf["access_key"]
MINIO_SECRET_KEY = minio_conf["secret_key"]
MINIO_CONNECTION = minio_conf["connection"]

if MINIO_CONNECTION == "api":
    MINIO_CONF = {
        "endpoint": MINIO_ADDRESS,
        "access_key": MINIO_ACCESS_KEY,
        "secret_key": MINIO_SECRET_KEY,
        "secure": False
    }
    MINIO_CLIENT = Minio(**MINIO_CONF)
elif MINIO_CONNECTION == "client":
    httpClient = urllib3.ProxyManager(
        MINIO_ADDRESS,
        timeout=urllib3.Timeout.DEFAULT_TIMEOUT,
        cert_reqs='CERT_NONE',
    )
    MINIO_CLIENT = Minio(MINIO_ADDRESS.split("//")[1],
                         access_key=MINIO_ACCESS_KEY,
                         secret_key=MINIO_SECRET_KEY,
                         secure=False,
                         http_client=httpClient)
else:
    print("Unknown minio connection")

INSIGHT_SERVER = CP["insight_server"]
AM_WAREHOUSE = CP.get("am_warehouse", "/tmp/file_models")
Path(AM_WAREHOUSE).mkdir(parents=True, exist_ok=True)
LOG_PATH = CP.get("log_path", "/tmp/logs")
Path(LOG_PATH).mkdir(parents=True, exist_ok=True)
